package com.ruanda.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanda.domain.Prod;
import com.ruanda.domain.ProdTagReference;
import com.ruanda.domain.Sku;
import com.ruanda.mapper.ProdMapper;
import com.ruanda.mapper.ProdTagReferenceMapper;
import com.ruanda.mapper.SkuMapper;
import com.ruanda.model.ChangeStock;
import com.ruanda.model.ProdChange;
import com.ruanda.model.SkuChange;
import com.ruanda.service.ProdService;
import com.ruanda.service.ProdTagReferenceService;
import com.ruanda.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 亦樂
 * @description 针对表【prod(商品)】的数据库操作Service实现
 * @createDate 2024-09-05 16:57:58
 */
@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod>
        implements ProdService {

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdTagReferenceMapper prodTagReferenceMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveProd(Prod prod) {
        // 新增商品
        prod.setShopId(1L);
        prod.setSoldNum(0);
        // 获取配置送方式
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        prod.setDeliveryMode(JSON.toJSONString(deliveryModeVo));
        prod.setCreateTime(new Date());
        prod.setUpdateTime(new Date());
        prod.setPutawayTime(new Date());
        prod.setVersion(0);
        int i = prodMapper.insert(prod);
        if (i > 0) {
            // 获取商品id
            Long prodId = prod.getProdId();
            // 获取商品分组标签id集合
            List<Long> tagIdList = prod.getTagList();
            // 判断是否有值
            if (!CollectionUtils.isEmpty(tagIdList) && tagIdList.size() != 0) {
                // 创建商品与分组标签关系集合对象
                List<ProdTagReference> prodTagReferences = new ArrayList<>();
                // 循环遍历商品分组标签id集合
                tagIdList.forEach(tagId -> {
                    // 创建商品与分组标签关系对象
                    ProdTagReference prodTagReference = new ProdTagReference();
                    prodTagReference.setProdId(prodId);
                    prodTagReference.setTagId(tagId);
                    prodTagReference.setShopId(1L);
                    prodTagReference.setCreateTime(new Date());
                    prodTagReference.setStatus(1);
                    // 将商品与分组标签关系对象添加到集合中
                    prodTagReferences.add(prodTagReference);
                });
                // 批量添加商品与分组标签关系集合
                prodTagReferenceService.saveBatch(prodTagReferences);
            }

            // 获取商品sku对象集合
            List<Sku> skuList = prod.getSkuList();
            // 判断是否有值
            if (!CollectionUtils.isEmpty(skuList) && skuList.size() != 0) {
                // 循环遍历商品sku对象集合
                skuList.forEach(sku -> {
                    sku.setProdId(prodId);
                    sku.setActualStocks(sku.getStocks());
                    sku.setCreateTime(new Date());
                    sku.setUpdateTime(new Date());
                    sku.setVersion(0);
                });
                // 批量添加商品sku对象
                skuService.saveBatch(skuList);
            }
        }
        return i;
    }

    @Override
    public Prod queryProdDetailById(Long prodId) {
        // 根据标识查询商品信息
        Prod prodDetailVo = prodMapper.selectById(prodId);
        // 根据商品标识查询商品与分组标签关系集合
        List<ProdTagReference> prodTagReferenceList = prodTagReferenceMapper.selectList(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId)
        );
        // 判断是否有值
        if (!CollectionUtils.isEmpty(prodTagReferenceList) && prodTagReferenceList.size() != 0) {
            // 从商品与分组标签关系集合中获取分组标签id集合
            List<Long> tagIdList = prodTagReferenceList.stream().map(ProdTagReference::getTagId).collect(Collectors.toList());
            prodDetailVo.setTagList(tagIdList);
        }
        // 根据商品标识查询商品sku对象集合
        List<Sku> skuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
        );
        if (!CollectionUtils.isEmpty(skuList) && skuList.size() != 0) {
            skuList.forEach(sku -> sku.setStocks(sku.getActualStocks()));
            prodDetailVo.setSkuList(skuList);
        }
        return prodDetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modifyProd(Prod prod) {
        // 获取商品标识
        Long prodId = prod.getProdId();
        // 删除原有的商品与分组标签关系
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId)
        );
        // 获取商品分组标签id集合
        List<Long> tagIdList = prod.getTagList();
        // 判断是否有值
        if (!CollectionUtils.isEmpty(tagIdList) && tagIdList.size() != 0) {
            // 创建商品与分组标签关系集合对象
            List<ProdTagReference> prodTagReferences = new ArrayList<>();
            // 循环遍历商品分组标签id集合
            tagIdList.forEach(tagId -> {
                // 创建商品与分组标签关系对象
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setProdId(prodId);
                prodTagReference.setTagId(tagId);
                prodTagReference.setShopId(1L);
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setStatus(1);
                // 将商品与分组标签关系对象添加到集合中
                prodTagReferences.add(prodTagReference);
            });
            // 批量添加商品与分组标签关系集合
            prodTagReferenceService.saveBatch(prodTagReferences);
        }
        // 删除原有商品sku对象
        skuMapper.delete(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
        );
        // 获取商品sku对象集合
        List<Sku> skuList = prod.getSkuList();
        // 判断是否有值
        if (!CollectionUtils.isEmpty(skuList) && skuList.size() != 0) {
            // 循环遍历商品sku对象集合
            skuList.forEach(sku -> {
                sku.setProdId(prodId);
                sku.setActualStocks(sku.getStocks());
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setVersion(0);
            });
            // 批量添加商品sku对象
            skuService.saveBatch(skuList);
        }
        // 更新商品信息
        prod.setUpdateTime(new Date());
        return prodMapper.updateById(prod);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer removeProdsByIds(List<Long> prodIds) {
        // 标识商品id集合批量删除商品与分组标签关系
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
                .in(ProdTagReference::getProdId, prodIds)
        );
        // 根据商品id集合批量删除商品sku对象集合
        skuMapper.delete(new LambdaQueryWrapper<Sku>()
                .in(Sku::getProdId, prodIds)
        );
        return prodMapper.deleteBatchIds(prodIds);
    }

    @Override
    public Prod queryWxProdInfoByProdId(Long prodId) {
        Prod prod = prodMapper.selectById(prodId);
        List<Sku> skuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
        );
        prod.setSkuList(skuList);
        return prod;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeProdAndSkuChangeStock(ChangeStock changeStock) {
        Boolean flag = false;
        // 获取商品sku购买数量对象
        List<SkuChange> skuChangeList = changeStock.getSkuChangeList();
        for (SkuChange skuChange : skuChangeList) {
            Long skuId = skuChange.getSkuId();
            Sku sku = skuMapper.selectById(skuId);
            Integer count = skuMapper.updateSkuStock(skuId, skuChange.getCount(), sku.getVersion());
            if (count == 1) {
                flag = true;
            } else {
                throw new RuntimeException("更新失败");
            }
        }
        // 获取商品prod购买数量对象
        List<ProdChange> prodChangeList = changeStock.getProdChangeList();
        for (ProdChange prodChange : prodChangeList) {
            Long prodId = prodChange.getProdId();
            Prod prod = prodMapper.selectById(prodId);
            Integer count = prodMapper.updateProdStock(prodId, prodChange.getCount(), prod.getVersion());
            if (count == 1) {
                flag = true;
            } else {
                throw new RuntimeException("更新失败");
            }
        }
        return flag;
    }
}




